package org.jeecg.modules.flowermater.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.netty.util.internal.AppendableCharSequence;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.FlowerStorehouse;
import org.jeecg.modules.flower.service.IFlowerStorehouseService;
import org.jeecg.modules.flowermater.entity.FlowerMaterialBook;
import org.jeecg.modules.flowermater.entity.FlowerMaterialCost;
import org.jeecg.modules.flowermater.service.IFlowerMaterialBookService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 采后物资台账表
 * @Author: jeecg-boot
 * @Date: 2022-07-13
 * @Version: V1.0
 */
@Api(tags = "采后物资台账表")
@RestController
@RequestMapping("/flowermater/flowerMaterialBook")
@Slf4j
public class FlowerMaterialBookController extends JeecgController<FlowerMaterialBook, IFlowerMaterialBookService> {
    @Autowired
    private IFlowerMaterialBookService flowerMaterialBookService;

    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;
    @Autowired
    private ISysDictService sysDictService;


    /**
     * 分页列表查询
     *
     * @param flowerMaterialBook
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "采后物资台账表-分页列表查询")
    @ApiOperation(value = "采后物资台账表-分页列表查询", notes = "采后物资台账表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(FlowerMaterialBook flowerMaterialBook,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
//		QueryWrapper<FlowerMaterialBook> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialBook, req.getParameterMap());
        LambdaQueryWrapper<FlowerMaterialBook> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(flowerMaterialBook.getName())) {
            queryWrapper.like(FlowerMaterialBook::getName, flowerMaterialBook.getName());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getCode())) {
            queryWrapper.like(FlowerMaterialBook::getCode, flowerMaterialBook.getCode());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getStorehouse())) {
            queryWrapper.eq(FlowerMaterialBook::getStorehouse, flowerMaterialBook.getStorehouse());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getCost())) {
            queryWrapper.eq(FlowerMaterialBook::getCost, flowerMaterialBook.getCost());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getSpecs())) {
            queryWrapper.like(FlowerMaterialBook::getSpecs, flowerMaterialBook.getSpecs());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getModelname())) {
            queryWrapper.like(FlowerMaterialBook::getModelname, flowerMaterialBook.getModelname());
        }

        Page<FlowerMaterialBook> page = new Page<FlowerMaterialBook>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
//        queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c " +
//                "where b.id = c.mainid and  flower_material_book.storehouse = b.code " +
//                "and personid = '" + sysUser.getId() + "'");
        queryWrapper.inSql(FlowerMaterialBook::getStorehouse ,"select b.code from flower_storehouse b , flower_storehouse_detail c " +
                "where b.id = c.mainid  and personid = '" + sysUser.getId() + "'");

        IPage<FlowerMaterialBook> pageList = flowerMaterialBookService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 不分页列表查询
     *
     * @param flowerMaterialBook
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "采后物资台账表-不分页列表查询-剩余数量大于0的")
    @ApiOperation(value = "采后物资台账表-不分页列表查询(剩余数量大于0的)", notes = "采后物资台账表-不分页列表查询剩余数量大于0的")
    @GetMapping(value = "/list1")
    public Result<?> queryList(FlowerMaterialBook flowerMaterialBook,
                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                               HttpServletRequest req) {
//        QueryWrapper<FlowerMaterialBook> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialBook, req.getParameterMap());
        LambdaQueryWrapper<FlowerMaterialBook> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(flowerMaterialBook.getName())) {
            queryWrapper.like(FlowerMaterialBook::getName, flowerMaterialBook.getName());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getCode())) {
            queryWrapper.like(FlowerMaterialBook::getCode, flowerMaterialBook.getCode());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getStorehouse())) {
            queryWrapper.eq(FlowerMaterialBook::getStorehouse, flowerMaterialBook.getStorehouse());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getCost())) {
            queryWrapper.eq(FlowerMaterialBook::getCost, flowerMaterialBook.getCost());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getSpecs())) {
            queryWrapper.like(FlowerMaterialBook::getSpecs, flowerMaterialBook.getSpecs());
        }
        if (StringUtils.isNotBlank(flowerMaterialBook.getModelname())) {
            queryWrapper.like(FlowerMaterialBook::getModelname, flowerMaterialBook.getModelname());
        }

        Page<FlowerMaterialBook> page = new Page<FlowerMaterialBook>(pageNo, pageSize);
        queryWrapper.gt(FlowerMaterialBook::getNum, 0);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.inSql(FlowerMaterialBook::getStorehouse,"select b.code from flower_storehouse b , flower_storehouse_detail c " +
                "where b.id = c.mainid   and personid = '" + sysUser.getId() + "'");
//        queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c " +
//                "where b.id = c.mainid  and flower_material_book.storehouse = b.code " +
//                "and personid = '" + sysUser.getId() + "'");
        List<FlowerMaterialBook> list = flowerMaterialBookService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 添加
     *
     * @param flowerMaterialBook
     * @return
     */
    @AutoLog(value = "采后物资台账表-添加")
    @ApiOperation(value = "采后物资台账表-添加", notes = "采后物资台账表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FlowerMaterialBook flowerMaterialBook) {
        flowerMaterialBookService.save(flowerMaterialBook);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param flowerMaterialBook
     * @return
     */
    @AutoLog(value = "采后物资台账表-编辑")
    @ApiOperation(value = "采后物资台账表-编辑", notes = "采后物资台账表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody FlowerMaterialBook flowerMaterialBook) {
        flowerMaterialBookService.updateById(flowerMaterialBook);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采后物资台账表-通过id删除")
    @ApiOperation(value = "采后物资台账表-通过id删除", notes = "采后物资台账表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        flowerMaterialBookService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "采后物资台账表-批量删除")
    @ApiOperation(value = "采后物资台账表-批量删除", notes = "采后物资台账表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.flowerMaterialBookService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采后物资台账表-通过id查询")
    @ApiOperation(value = "采后物资台账表-通过id查询", notes = "采后物资台账表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerMaterialBook flowerMaterialBook = flowerMaterialBookService.getById(id);
        if (flowerMaterialBook == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(flowerMaterialBook);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerMaterialBook
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerMaterialBook flowerMaterialBook) {
        return super.exportXls(request, flowerMaterialBook, FlowerMaterialBook.class, "采后物资台账表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FlowerMaterialBook.class);
    }

    /**
     * 成本查询
     *
     * @param storehouse
     * @param cost
     * @param sDate
     * @param eDate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "采后物资台账表-成本查询")
    @ApiOperation(value = "采后物资台账表-成本查询", notes = "采后物资台账表-成本查询")
    @GetMapping(value = "/queryMaterCost")
    public Result<?> queryMaterCost(
            @RequestParam(name = "storehouse", defaultValue = "") String storehouse,
            @RequestParam(name = "cost", defaultValue = "") String cost,
            @RequestParam(name = "sDate", defaultValue = "") String sDate,
            @RequestParam(name = "eDate", defaultValue = "") String eDate,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isBlank(sDate)) {
            sDate = simpleDateFormat.format(calendar.getTime());
        }
        if (StringUtils.isBlank(eDate)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            eDate = simpleDateFormat.format(calendar.getTime());
        }
        Page<FlowerMaterialCost> page = new Page<FlowerMaterialCost>(pageNo, pageSize);
        IPage<FlowerMaterialCost> pageList = flowerMaterialBookService.queryMaterCost(page, storehouse, cost, sDate, eDate);
        return Result.ok(pageList);
    }

    @RequestMapping(value = "/exportXls2")
    public ModelAndView exportXls(HttpServletRequest request,
                                  @RequestParam(name = "storehouse", defaultValue = "") String storehouse,
                                  @RequestParam(name = "cost", defaultValue = "") String cost,
                                  @RequestParam(name = "sDate", defaultValue = "") String sDate,
                                  @RequestParam(name = "eDate", defaultValue = "") String eDate) {
//		 LoginUser sysUser = JwtUtil.getLoginUser();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isBlank(sDate)) {
            sDate = simpleDateFormat.format(calendar.getTime());
        }
        if (StringUtils.isBlank(eDate)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            eDate = simpleDateFormat.format(calendar.getTime());
        }
        Page<FlowerMaterialCost> page = new Page<FlowerMaterialCost>(1, 99999);
        IPage<FlowerMaterialCost> pageList = flowerMaterialBookService.queryMaterCost(page, storehouse, cost, sDate, eDate);
        List<FlowerMaterialCost> records = pageList.getRecords();
        for (FlowerMaterialCost flowerMaterialCost : records) {
            String cost1 = flowerMaterialCost.getCost();
            String storehouse1 = flowerMaterialCost.getStorehouse();

            QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("code", storehouse1);
            FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
            flowerMaterialCost.setStorehouse(house.getName());

//			 Result<String> dd = sysDictServiceClient.getDictTextOpen("ch_cost", cost1);
            String costname = sysDictService.queryDictTextByKey("ch_cost", cost1);
//			 flowerMaterialCost.setCost( dd.getResult());
            flowerMaterialCost.setCost(costname);
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "采后物资成本"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, FlowerMaterialCost.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采后物资成本报表", "导出人:" + sysUser.getRealname(), "采后物资成本"));
        mv.addObject(NormalExcelConstants.DATA_LIST, records);
        return mv;
    }
}
